package com.springJms.demo;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTest1 {
	@Test
	public void test_Producer() throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		PooledConnectionFactory factory = (PooledConnectionFactory) context.getBean("pooledConnectionFactory");
		Destination queue = (ActiveMQQueue) context.getBean("queueDestination");
		Connection connection = factory.createConnection();
		connection.start();
		
		Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
		MessageProducer producer = session.createProducer(queue);
		
		TextMessage message = session.createTextMessage();
		message.setText("My name is YQ");
		
		producer.send(message);
		
		session.commit();
		producer.close();
		session.close();
		connection.close();
		
		System.out.println("End");
		
		factory.stop();
	}
	
	@Test
	public void test_customer() throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		PooledConnectionFactory factory = (PooledConnectionFactory) context.getBean("pooledConnectionFactory");
		Destination queue = (ActiveMQQueue) context.getBean("queueDestination");
		Connection connection = factory.createConnection();
		connection.start();
		
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		MessageConsumer consumer = session.createConsumer(queue);
		TextMessage message = (TextMessage) consumer.receive();
		
		String j = message.getText();
		System.out.println(j);
		
		JSONObject json = new JSONObject(j);
		System.out.println(json.get("ip"));
		System.out.println(json.get("name"));
		System.out.println(json.get("pswd"));
		System.out.println(json.get("timestamp"));
		
		session.commit();
		System.out.println("=========================");
		
	}
}
